﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using UComment.Domain;
using umbraco.DataLayer;
using umbraco.cms.businesslogic.web;
using System.Data;
using System.Collections;
using umbraco;

namespace UComment.Dashboard
{
    public partial class UCommentModeration : UserControl
    {
        readonly ISqlHelper _sqlHelper = 
            DataLayerHelper.CreateSqlHelper(GlobalSettings.DbDSN);

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            rptPages.ItemCommand += RptPagesItemCommand;
        }

        void RptPagesItemCommand(object source, RepeaterCommandEventArgs e)
        {
            CurrentPage = Convert.ToInt32(e.CommandArgument) - 1;
            BindData();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            Filter = "where spam != 1";
            btnApproved.Enabled = false;

            BindData();
        }

        private void BindData()
        {
            var rr = _sqlHelper.ExecuteReader(
                string.Format(
                "select * from comment {0} order by created desc", Filter));

            var commentDt = new DataTable("Comments");
            commentDt.Columns.Add("id", Type.GetType("System.Int32"));
            commentDt.Columns.Add("nodeid", Type.GetType("System.Int32"));
            commentDt.Columns.Add("name", Type.GetType("System.String"));
            commentDt.Columns.Add("email", Type.GetType("System.String"));
            commentDt.Columns.Add("website", Type.GetType("System.String"));
            commentDt.Columns.Add("comment", Type.GetType("System.String"));
            commentDt.Columns.Add("spam", Type.GetType("System.Boolean"));
            commentDt.Columns.Add("ham", Type.GetType("System.Boolean"));
            commentDt.Columns.Add("created",Type.GetType("System.DateTime"));

            while (rr.Read())
            {
                var dr = commentDt.NewRow();
                dr["id"] = rr.GetInt("id");
                dr["nodeid"] = rr.GetInt("nodeid");
                dr["name"] = rr.GetString("name");
                dr["email"] = rr.GetString("email");
                dr["website"] = rr.GetString("website");
                dr["comment"] = rr.GetString("comment");
                dr["spam"] = rr.IsNull("spam") == true ? false : rr.GetBoolean("spam");
                dr["ham"] = rr.IsNull("ham") == true ? false : rr.GetBoolean("ham");
                dr["created"] = rr.GetDateTime("created");

                
                commentDt.Rows.Add(dr);
            }
            
            var pgitems = new PagedDataSource
                              {
                                  DataSource = commentDt.DefaultView,
                                  AllowPaging = true,
                                  PageSize = 25,
                                  CurrentPageIndex = CurrentPage
                              };

            rptComments.DataSource = pgitems;
            rptComments.DataBind();

            if (pgitems.PageCount > 1)
            {

                var pages = new ArrayList();
                for (var i = 0; i < pgitems.PageCount; i++)
                    pages.Add((i + 1).ToString());

                rptPages.DataSource = pages;
                rptPages.DataBind();
                rptPages.Visible = true;
            }
            else
            {
                rptPages.Visible = false;

            }
        }

        public int CurrentPage
        {
            get
            {
                // look for current page in ViewState
                var o = ViewState["_CurrentPage"];
                if (o == null)
                    return 0; // default page index of 0

                return (int)o;
            }
            set
            {
                ViewState["_CurrentPage"] = value;
            }
        }

        protected void BtnDeleteClick(object sender, EventArgs e)
        {
           new Comment(Convert.ToInt32(((LinkButton)sender).CommandArgument)).Delete();
           BindData();
        }

        protected void BtnToggleStateClick(object sender, EventArgs e)
        {
            var c = new Comment(Convert.ToInt32(((LinkButton)sender).CommandArgument));

            if (((LinkButton)sender).CommandName == "True")
            {
                c.MarkAsHam();
                var checker = Config.GetChecker();

                if (checker != null)
                {
                    checker.MarkAsHam(c.ParentNodeId, c.Name, c.Email, c.Website, c.CommenText);
                }
               
            }
            else
            {
                c.MarkAsSpam();
                var checker = Config.GetChecker();

                if(checker != null)
                {
                    checker.MarkAsSpam(c.ParentNodeId, c.Name, c.Email, c.Website, c.CommenText);
                }
            }

            BindData();
        }

        public string GetPageDetails(object nodeid)
        {
            int id;
            if(int.TryParse(nodeid.ToString(),out id))
            {
                try
                {
                    var page = new Document(id);

                    return string.Format(
                        "<a href='{0}' target='_blank'>{1}</a>",
                        library.NiceUrl(page.Id), page.Text);
                }
                catch { return string.Empty; }
            }

            return string.Empty;
        }

        public string GetToggleStateText(object spam)
        {
            bool isspam ;
            if (bool.TryParse(spam.ToString(), out isspam))
            {
                return isspam ? "Mark as ham" : "Mark as spam";
            }
            return string.Empty;
        }

        public string Filter
        {
            get
            {               
                var o = ViewState["Filter"];
                if (o == null)
                    return string.Empty;

                return (string)o;
            }

            set
            {
                ViewState["Filter"] = value;
            }
        }

        protected void BtnApprovedClick(object sender, EventArgs e)
        {
            btnApproved.Enabled = false;
            btnSpam.Enabled = true;
            btnAll.Enabled = true;

            Filter = "where spam != 1";
            CurrentPage = 0;
            BindData();
        }

        protected void BtnSpamClick(object sender, EventArgs e)
        {
            btnApproved.Enabled = true;
            btnSpam.Enabled = false;
            btnAll.Enabled = true;

            Filter = "where spam = 1";

            CurrentPage = 0;
            BindData();
        }

        protected void BtnAllClick(object sender, EventArgs e)
        {
            btnApproved.Enabled = true;
            btnSpam.Enabled = true;
            btnAll.Enabled = false;

            Filter = "";
            CurrentPage = 0;
            BindData();
        }

        protected void BtnDeleteSelectedClick(object sender, EventArgs e)
        {
            foreach (RepeaterItem item in rptComments.Items)
            {
                var chk = (CheckBox)item.FindControl("cbSelectComment");

                if (chk.Checked)
                {
                     new Comment(Convert.ToInt32(((Label)item.FindControl("lblID")).Text)).Delete();
                }

            }
            BindData();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Write("fuckkkk");
        }
    }
}